package com.dd.ent.car.ui.widget.webview;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import com.pp.ent.base.common.SafeHandlerDispatch;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

final class DefaultJsInterface extends BaseJsInterface {
    private List<JsMessageInterceptor> mMessageInterceptorList = new ArrayList<>();
    private final SafeHandlerDispatch mMessageListener = new SafeHandlerDispatch(){

        @Override
        public void handleMessage(Message msg) {
        }
    };
    private final Handler mOperateHandler = new SafeHandlerDispatch();

    public DefaultJsInterface(Context context, CustomWebView webView) {
        super(context, webView);
    }

    public void addInterceptor(JsMessageInterceptor interceptor) {
        mMessageInterceptorList.add(interceptor);
    }

    public void removeInterceptor(JsMessageInterceptor interceptor) {
        mMessageInterceptorList.remove(interceptor);
    }

    public void clearInterceptors() {
        mMessageInterceptorList.clear();
    }

    private boolean interceptMessage(MethodName methodName, JSONObject paramJson, final String callback) throws JSONException {
        if (!mMessageInterceptorList.isEmpty()) {
            for (JsMessageInterceptor interceptor : mMessageInterceptorList) {
                boolean isIntercept = interceptor.handleMessage(methodName, paramJson, callback);
                if (isIntercept) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected boolean handleMessage(MethodName methodName, JSONObject paramJson, final String callback) throws JSONException {
        boolean isIntercept = interceptMessage(methodName, paramJson, callback);
        if (isIntercept) {
            return true;
        }
        boolean isHandle = true;
        switch (methodName) {
            default:
                isHandle = false;
                break;
        }
        return isHandle;
    }

}
